import { Button, Toast } from 'antd-mobile'
import style from './index.module.less'
import {getDefinceRequest} from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { useEffect, useState } from 'react'
import PageLoading from '@components/pageLoading'
import Item from './components/item'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import { push } from '@src/redux/reducers/pages'


// 获取请求列表的答辩信息，并过滤没有答辩的请求
async function initDefinceList (caseid, claims) {
  const res = await Promise.all(claims.map(async claim => await getDefinceRequest(caseid, claim.id)))
  const result = []
  res.forEach((list, index) => {
    if (list.length > 0) {
      claims[index].defince = list
      result.push(claims[index])
    }
  })
  return result
}

// 初始化仲裁请求的答辩
async function initClaimsDefince (caseid, claims, setClaims) {
  const [e, d] = await awaitWrap(initDefinceList(caseid, claims))
  if (e === null && d !== null) {
    setClaims(d)
  }
}

async function initData (c, setClaims, setCclaims, setLoading) {
  setLoading(true)
  await Promise.all([initClaimsDefince(c.id, c.claims, setClaims), initClaimsDefince(c.id, c.cclaims, setCclaims)])
  setLoading(false)
}

function Main ({ data }) {
  const dispatch = useAppDispatch()
  const version = useAppSelector(state => state.cases.caseEditVersion)
  const [loading, setLoading] = useState(false)
  const [claims, setClaims] = useState([])
  const [cclaims, setCclaims] = useState([])
  useEffect(() => {
    if (data) {
      initData(data, setClaims, setCclaims, setLoading).catch(e => console.error(e))
    }
  }, [data, version])
  if (loading) {
    return (
      <PageLoading />
    )
  }
  return (
    <div className={style.container}>
      {
        claims.map((li, i) => {
          return (
            <Item data={li} key={i} />
          )
        })
      }
      {
        cclaims.map((li, i) => {
          return (
            <Item data={li} key={i} anti />
          )
        })
      }
      <div className={style.btn}>
        <Button color='primary' block onClick={() => {
          dispatch(push({ element: 'addDefence', meta: { caseid: data.id } }))
        }}>添加答辩</Button>
      </div>
    </div>
  )
}

export default Main
